#!/bin/bash

# 1 = Name of the application
# 2 = System extension bundle id

# TODO: Temporarily disabling stop on failure because launchctl unload sometimes returns code 141.
# This appears to happen when it tries to unload the launch agent which launched the top process on the ancestry of this process
# In fact, the unloading is successful despite the error code.
# For now, it seems ok to disable stopping in case of error considering that at this point the user can't react to the error anyway.
# set -e -o pipefail

LOG_FILE=/tmp/uninstall.log
echo "Sleeping 5 seconds" >$LOG_FILE
sleep 5

if [ -d "/Applications/$1.app" ]
then
    echo "/Applications/$1.app exists, abort!" >>$LOG_FILE
    exit
fi

# Get the application name from command-line argument
applicationName="$1"

# Construct the daemonsDir path
daemonsDir="/Library/Application Support/$applicationName/SafetyBackup.app/Contents/Helpers/$applicationName.app/Contents/Daemons"

# Check if the directory exists
if [ -d "$daemonsDir" ]; then
    
    # Iterate over directories ending with .app
    for daemonDirPath in "$daemonsDir"/*.app; do
        [ -d "$daemonDirPath" ] || continue # Check if it's a directory
        daemonDirName=$(basename "$daemonDirPath")
        daemonId="${daemonDirName%.app}"  # Remove .app extension
        daemonUninstallerPath="$daemonsDir/$daemonId.app/Contents/Library/uninstaller"

        # Run the uninstaller and capture its output
        echo "Running uninstaller for $daemonId..." >>$LOG_FILE
        uninstallerOutput=$("$daemonUninstallerPath" "$daemonId" 2>&1)
        echo "Uninstaller output for $daemonId:" >>$LOG_FILE
        echo "$uninstallerOutput" >>$LOG_FILE
    done
else
    echo "No daemons!" >>$LOG_FILE
fi

echo "Removing \"/Library/Application Support/SafeCentral Secure Browser\"" >>$LOG_FILE
rm -rf "/Library/Application Support/SafeCentral Secure Browser"

echo "Removing \"/Library/Application Support/$applicationName\"" >>$LOG_FILE
rm -rf "/Library/Application Support/$applicationName"

echo "Removing \"/Library/LaunchAgents/$applicationName Uninstall Monitor.plist\"" >>$LOG_FILE
rm -rf "/Library/LaunchAgents/$applicationName Uninstall Monitor.plist"

echo "Removing defaults for $2" >>$LOG_FILE
defaults delete $2

echo "Removing monitor from launchd">>$LOG_FILE
launchctl remove "${applicationName}UninstallMonitor"
echo "Final cleanup complete" >>$LOG_FILE
